package com.easyskool.excel.util;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URI;

import javax.mail.internet.MimeMultipart;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.fileupload.FileItem;

import com.northconcepts.datapipeline.core.DataException;
import com.northconcepts.datapipeline.core.DataReader;
import com.northconcepts.datapipeline.core.DataWriter;
import com.northconcepts.datapipeline.core.RecordList;
import com.northconcepts.datapipeline.csv.CSVReader;
import com.northconcepts.datapipeline.csv.CSVWriter;
import com.northconcepts.datapipeline.excel.ExcelDocument;
import com.northconcepts.datapipeline.excel.ExcelDocument.ProviderType;
import com.northconcepts.datapipeline.excel.ExcelReader;
import com.northconcepts.datapipeline.excel.ExcelWriter;
import com.northconcepts.datapipeline.jdbc.JdbcReader;
import com.northconcepts.datapipeline.jdbc.JdbcWriter;
import com.northconcepts.datapipeline.job.JobTemplate;
import com.northconcepts.datapipeline.memory.MemoryWriter;
import com.northconcepts.datapipeline.transform.BasicFieldTransformer;
import com.northconcepts.datapipeline.transform.CopyField;
import com.northconcepts.datapipeline.transform.IncludeFields;
import com.northconcepts.datapipeline.transform.SetCalculatedField;
import com.northconcepts.datapipeline.transform.TransformingReader;

@Path("/events")
public class EventsResource {
    
    private static final DB db = new DB();

    static {
        // Create EVENT table
        db.executeUpdate("CREATE TABLE EVENT (" + 
        		"    EVENT_ID INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1) not null, " + 
        		"    EVENT_TYPE VARCHAR(20)," + 
        		"    TITLE VARCHAR(200)," + 
        		"    SUMMARY LONGVARCHAR," + 
        		"    LOCATION VARCHAR(8000)," + 
                "    START_TIME DATETIME," + 
        		"    DURATION_MINUTES NUMERIC(6,0)" + 
        		")");
        
        // Populate EVENT table with data
        for (int i = 0; i < 10; i++) {
            db.executeUpdate("INSERT INTO EVENT(EVENT_TYPE, TITLE, SUMMARY, LOCATION, START_TIME, DURATION_MINUTES) " + 
            		"  VALUES('Business', 'Title "+i+"', 'Summary "+i+"', 'Location "+i+"', '2012-12-03 8:45:00', 135)");
        }
    }
    
    private DataReader getEvents() {
        DataReader reader = new JdbcReader(db.getConnection(), "SELECT * FROM EVENT");
        
        reader = new TransformingReader(reader)
            .add(new CopyField("DURATION_MINUTES", "DURATION", true))
            .add(new BasicFieldTransformer("DURATION").numberToMinutes())
            ;
        
        reader = new TransformingReader(reader)
            .add(new SetCalculatedField("END_TIME", "START_TIME + DURATION"))
            ;
    
        reader = new TransformingReader(reader)
            .add(new CopyField("START_TIME", "START", true))
            .add(new BasicFieldTransformer("START").dateTimeToString("EE MMM d, yyyy 'at' h:mm a"))
            ;
        
        reader = new TransformingReader(reader)
            .add(new CopyField("END_TIME", "END", true))
            .add(new BasicFieldTransformer("END").dateTimeToString("h:mm a"))
            ;
    
        return reader;
    }

    @GET
    @Path("/events")
    public Response getHome() throws Throwable {
        // Redirect "/" to "/events"
        return Response.seeOther(new URI("/events/events1")).build();
    }

    @GET
    @Path("/events1")
    public void getEventsAsHtml(
            @Context HttpServletRequest request,
            @Context HttpServletResponse response) throws Throwable {
        System.out.println("#################################here ");
        DataReader reader = getEvents();
        MemoryWriter writer = new  MemoryWriter();
        JobTemplate.DEFAULT.transfer(reader, writer);
       
        RecordList recordList = writer.getRecordList();
        request.setAttribute("recordList", recordList);
        request.getRequestDispatcher("/WebPages/Webadmin/events.jsp").forward(request, response);
    }

    @GET
    @Path("/events1.excel")
    public Response getEventsAsExcel(@Context HttpServletResponse response) throws Throwable {
        DataReader reader = getEvents();

        ExcelDocument excelDocument = new ExcelDocument();
        DataWriter writer = new ExcelWriter(excelDocument).setFieldNamesInFirstRow(true);
        
        JobTemplate.DEFAULT.transfer(reader, writer);
        
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=\"events.xls\"");
        OutputStream outputStream = response.getOutputStream();
        excelDocument.save(outputStream);

        return Response.ok().build();
    }

    @GET
    @Path("/events1.csv")
    public Response getEventsAsCsv(@Context HttpServletResponse response) throws Throwable {
        DataReader reader = getEvents();

        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment; filename=\"events.csv\"");
        PrintWriter printWriter = response.getWriter();
        DataWriter writer = new CSVWriter(printWriter).setFieldNamesInFirstRow(true);
        
        JobTemplate.DEFAULT.transfer(reader, writer);
        
        return Response.ok().build();
    }

    
    @POST
    @Path("/events2")
    @Consumes(MediaType.MULTIPART_FORM_DATA)     
    @Produces(MediaType.TEXT_PLAIN)

    	  public Response uploadFile(final MimeMultipart  file) {
    	if (file == null) {
        return Response.status(Response.Status.BAD_REQUEST).entity("Must supply a valid file").build();
    	}
      try {
        for (int i = 0; i < file.getCount(); i++) {
          System.out.println("file"+file);
        }
        return Response.ok("done").build();
      } catch (final Exception e) {
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e).build();
      }
    }
    
//    @POST
//    @Path("/events2")
//    @SuppressWarnings("unchecked")
//    @Consumes(MediaType.MULTIPART_FORM_DATA)
//    public Response uploadEvents(@FormDataParam("file") InputStream uploadedInputStream,
//    		@FormDataParam("file") FormDataContentDisposition fileDetail ) throws Throwable {
////        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
//        System.out.println("#########################Uploaaadd ");
////        if (!isMultipart) {
////            return Response.ok("Not multipart request").build();
////        }
//        //System.out.println("#################################="+request);
//        //FileItemFactory factory = new DiskFileItemFactory();
////        ServletFileUpload upload = new ServletFileUpload(factory);
////        List<FileItem> files = upload.parseRequest(request);
//        
//        System.out.println("#################################="+fileDetail.getFileName());
//        
//        saveEventsToDB(uploadedInputStream, fileDetail.getFileName());
////        List<FileItem> files = null;
////        try{
////         files = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
////        }catch(Exception e){
////        	e.printStackTrace();
////        }
////        System.out.println("files : "+files);
////        for (FileItem file : files) {
////            saveEvents(file);
////        }
//    	
////    	if (ServletFileUpload.isMultipartContent(request)) {
////    		InputStream is =  null;
////    	    ServletFileUpload fileUpload = new ServletFileUpload();
////    	    FileItemIterator items = fileUpload.getItemIterator(request);
////    	    while (items.hasNext()) {
////    	    FileItem item = (FileItem)items.next();
////    	    
////    	        saveEvents(item);
////    	    
////    	    }
////    	}
//        
//        return Response.seeOther(new URI("/events/events1")).build();
//    }

    private void saveEventsToDB(InputStream inputStream, String fileName) throws Throwable {
        
        System.out.println("#################################Save Eventss");
        
        //String fileName = fileName;
        DataReader reader;
        
        if (fileName.endsWith(".csv")) {
            reader = new CSVReader(new InputStreamReader(inputStream)).setFieldNamesInFirstRow(true);
        } else if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
            ExcelDocument excelDocument = new ExcelDocument(fileName.endsWith(".xlsx")?ProviderType.POI_XSSF:ProviderType.POI);
            excelDocument.open(inputStream);
            reader = new ExcelReader(excelDocument).setFieldNamesInFirstRow(true);
        } else {
            throw new DataException("unknown file type: expected .csv, .xls, or .xlsx file extension").set("fileName", fileName);
        }
        
        reader = new TransformingReader(reader).add(new IncludeFields("EVENT_TYPE", "TITLE", "SUMMARY", "LOCATION", "START_TIME", "DURATION_MINUTES"));
        DataWriter writer = new JdbcWriter(db.getConnection(), "EVENT");
        
        JobTemplate.DEFAULT.transfer(reader, writer);
    }
    
    private void saveEvents(FileItem file) throws Throwable {
        if (file.isFormField()) {
            return;
        }
        System.out.println("#################################Save Eventss");
        
        String fileName = file.getName();
        DataReader reader;
        
        if (fileName.endsWith(".csv")) {
            reader = new CSVReader(new InputStreamReader(file.getInputStream())).setFieldNamesInFirstRow(true);
        } else if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
            ExcelDocument excelDocument = new ExcelDocument(fileName.endsWith(".xlsx")?ProviderType.POI_XSSF:ProviderType.POI);
            excelDocument.open(file.getInputStream());
            reader = new ExcelReader(excelDocument).setFieldNamesInFirstRow(true);
        } else {
            throw new DataException("unknown file type: expected .csv, .xls, or .xlsx file extension").set("fileName", fileName);
        }
        
        reader = new TransformingReader(reader).add(new IncludeFields("EVENT_TYPE", "TITLE", "SUMMARY", "LOCATION", "START_TIME", "DURATION_MINUTES"));
        DataWriter writer = new JdbcWriter(db.getConnection(), "EVENT");
        
        JobTemplate.DEFAULT.transfer(reader, writer);
    }
    
}
